﻿#pragma once
#include <iostream>
#include <fstream>

class Logger {
private:
  std::string logFilePath;
  std::ofstream logFile;
  std::string timeStr;

  // 确保文件已打开
  void ensureFileOpen() {
    if (!logFile.is_open()) {
      logFile.open(logFilePath, std::ios::app | std::ios::binary);
      if (!logFile.is_open()) {
        std::cerr << "无法打开日志文件: " << logFilePath << std::endl;
      }
      OutPutCurrTimeInfo();
      std::cerr << "run error, log file open state " << logFilePath << std::endl;
    }
  }
  void OutPutCurrTimeInfo();
public:
  // 构造函数，初始化日志文件路径
  Logger();

  ~Logger() {
    if (logFile.is_open()) {
      logFile.close();
    }
  }
  std::string GetTimeStr()const { return timeStr; }
  // 日志记录方法，将消息追加到日志文件
  void log(const std::string& message) {
    try {
      ensureFileOpen();
      logFile << message << std::endl;
      // 关闭文件
      //logFile.close();
    }
    catch (const std::exception& e) {
      std::cerr << "写入日志文件时出错: " << e.what() << std::endl;
    }
  }

  // 重载 << 操作符
  template<typename T>
  Logger& operator<<(const T& value) {
    ensureFileOpen();
    if (logFile.is_open()) {
      logFile << value;
    }
    return *this;
  }

  // 重载 << 操作符，处理 std::endl
  Logger& operator<<(std::ostream& (*manipulator)(std::ostream&)) {
    ensureFileOpen();
    if (logFile.is_open()) {
      manipulator(logFile);
    }
    return *this;
  }
};
